package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"pay/alipay"
	"pay/wechatpay"
)

type Pay struct {
}

type PrepayResult struct {
	Type string `json:"type"`
	Url  string `json:"url"`
}

func (*Pay) PrePay(c *gin.Context) (interface{}, error) {
	list := make([]PrepayResult, 0)
	var nativePrePay wechatpay.NativePrePay
	err := c.ShouldBind(&nativePrePay)
	if err != nil {
		return list, err
	}
	url, err := nativePrePay.Prepay()
	if err != nil {
		return list, err
	}
	list = append(list, PrepayResult{
		Type: "wechat",
		Url:  url,
	})
	var alipayNative alipay.NativePrePay
	alipayNative.OutTradeNo = nativePrePay.OutTradeNo
	alipayNative.Total = nativePrePay.Total
	alipayNative.TimeExpire = nativePrePay.TimeExpire
	alipayNative.Description = nativePrePay.Description
	alipayNative.NotifyUrl = nativePrePay.NotifyUrl
	alipayNative.ReturnUrl = nativePrePay.ReturnUrl
	url1, err := alipayNative.Native()
	if err != nil {
		return list, err
	}
	list = append(list, PrepayResult{
		Type: "alipay",
		Url:  url1,
	})
	return list, nil
}

func (*Pay) Refund(c *gin.Context) (interface{}, error) {
	tp := c.Param("type")
	switch tp {
	case "wechat":
		var refund wechatpay.Refund
		err := c.ShouldBind(&refund)
		if err != nil {
			return "", err
		}
		return refund.Done()
	case "alipay":
		var refund alipay.Refund
		err := c.ShouldBind(&refund)
		if err != nil {
			return "", err
		}
		return refund.Done()
	}
	return 0, errors.New("没有支付类型")
}

func (*Pay) Close(c *gin.Context) (interface{}, error) {
	var refund wechatpay.Close
	err := c.ShouldBind(&refund)
	if err != nil {
		return "", err
	}
	var alipayRefund alipay.Close
	_, err = alipayRefund.NativeCloseOrder()
	if err != nil {
		return "", err
	}
	return refund.NativeCloseOrder()
}

func (*Pay) Query(c *gin.Context) (interface{}, error) {
	tp := c.Param("type")
	switch tp {
	case "wechat":
		no := c.DefaultQuery("outTradeNo", "")
		if no == "" {
			return "", errors.New("没有订单号")
		}
		return wechatpay.FindByOutTradeNo(no)
	case "alipay":
		no := c.DefaultQuery("outTradeNo", "")
		if no == "" {
			return "", errors.New("没有订单号")
		}
		return alipay.FindByOutTradeNo(no)
	}
	return 0, errors.New("没有支付类型")
}

func (*Pay) Callback(c *gin.Context) (interface{}, error) {
	tp := c.Param("type")
	if tp == "alipay" {
		return alipay.Callback(c.Request)
	} else {
		return wechatpay.Callback(c.Request)
	}

}

func (*Pay) Test(c *gin.Context) (interface{}, error) {
	var nativePrePay wechatpay.CallbackContent
	err := c.ShouldBind(&nativePrePay)
	if err != nil {
		return nativePrePay, err
	}
	fmt.Println(nativePrePay)
	return nativePrePay, nil
}
